using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Mark.Data;
using Mark.Models;

namespace Mark.Services;

/// <summary>
/// 数据库初始化服务
/// </summary>
public class DatabaseInitializer
{
    private readonly MarkDbContext _context;
    private readonly ILogger<DatabaseInitializer> _logger;

    public DatabaseInitializer(MarkDbContext context, ILogger<DatabaseInitializer> logger)
    {
        _context = context;
        _logger = logger;
    }

    /// <summary>
    /// 初始化数据库
    /// </summary>
    public async Task InitializeAsync()
    {
        try
        {
            // 确保数据库被创建
            await _context.Database.EnsureCreatedAsync();
            _logger.LogInformation("数据库初始化完成");

            // 插入预制数据
            await SeedDataAsync();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "数据库初始化失败");
            throw;
        }
    }

    /// <summary>
    /// 插入预制数据
    /// </summary>
    private async Task SeedDataAsync()
    {
        // 检查是否已经有数据
        if (await _context.Providers.AnyAsync())
        {
            _logger.LogInformation("数据库已包含数据，跳过预制数据插入");
            return;
        }

        _logger.LogInformation("开始插入预制数据...");

        // 1. 创建默认用户
        var defaultUser = new User
        {
            Id = "default-user",
            Username = "admin",
            DisplayName = "管理员",
            Email = "admin@mark.local",
            Status = "Active"
        };
        _context.Users.Add(defaultUser);

        // 2. 创建AI提供商
        var providers = new List<Provider>
        {
            new Provider
            {
                Id = "openai",
                Name = "openai",
                DisplayName = "OpenAI",
                Description = "OpenAI提供的GPT系列模型",
                BaseUrl = "https://api.openai.com",
                Status = "Active",
                SupportedFeatures = "Chat,Completion,Vision,Function",
                Priority = 1
            },
            new Provider
            {
                Id = "deepseek",
                Name = "deepseek",
                DisplayName = "DeepSeek",
                Description = "DeepSeek提供的AI模型",
                BaseUrl = "https://api.deepseek.com",
                Status = "Active",
                SupportedFeatures = "Chat,Completion",
                Priority = 2
            },
            new Provider
            {
                Id = "claude",
                Name = "claude",
                DisplayName = "Claude",
                Description = "Anthropic提供的Claude模型",
                BaseUrl = "https://api.anthropic.com",
                Status = "Active",
                SupportedFeatures = "Chat,Vision",
                Priority = 3
            },
            new Provider
            {
                Id = "gemini",
                Name = "gemini",
                DisplayName = "Google Gemini",
                Description = "Google提供的Gemini模型",
                BaseUrl = "https://generativelanguage.googleapis.com",
                Status = "Active",
                SupportedFeatures = "Chat,Vision",
                Priority = 4
            }
        };
        _context.Providers.AddRange(providers);

        // 3. 创建AI模型
        var models = new List<Model>
        {
            // OpenAI Models
            new Model
            {
                Id = "gpt-4o",
                Name = "gpt-4o",
                DisplayName = "GPT-4o",
                Description = "OpenAI最新的多模态模型",
                Type = "Chat",
                ContextLength = 128000,
                InputPrice = 0.005m,
                OutputPrice = 0.015m,
                Status = "Active",
                SupportedFeatures = "Vision,Function",
                Priority = 1,
                ProviderId = "openai"
            },
            new Model
            {
                Id = "gpt-4-turbo",
                Name = "gpt-4-turbo",
                DisplayName = "GPT-4 Turbo",
                Description = "OpenAI的高性能GPT-4模型",
                Type = "Chat",
                ContextLength = 128000,
                InputPrice = 0.01m,
                OutputPrice = 0.03m,
                Status = "Active",
                SupportedFeatures = "Vision,Function",
                Priority = 2,
                ProviderId = "openai"
            },
            // DeepSeek Models
            new Model
            {
                Id = "deepseek-chat",
                Name = "deepseek-chat",
                DisplayName = "DeepSeek Chat",
                Description = "DeepSeek的对话模型",
                Type = "Chat",
                ContextLength = 32768,
                InputPrice = 0.0007m,
                OutputPrice = 0.002m,
                Status = "Active",
                SupportedFeatures = "Chat",
                Priority = 1,
                ProviderId = "deepseek"
            },
            new Model
            {
                Id = "deepseek-coder",
                Name = "deepseek-coder",
                DisplayName = "DeepSeek Coder",
                Description = "DeepSeek的编程专用模型",
                Type = "Chat",
                ContextLength = 16384,
                InputPrice = 0.0007m,
                OutputPrice = 0.002m,
                Status = "Active",
                SupportedFeatures = "Chat,Code",
                Priority = 2,
                ProviderId = "deepseek"
            },
            // Claude Models
            new Model
            {
                Id = "claude-3-opus",
                Name = "claude-3-opus",
                DisplayName = "Claude 3 Opus",
                Description = "Anthropic最强大的Claude模型",
                Type = "Chat",
                ContextLength = 200000,
                InputPrice = 0.015m,
                OutputPrice = 0.075m,
                Status = "Active",
                SupportedFeatures = "Vision",
                Priority = 1,
                ProviderId = "claude"
            },
            new Model
            {
                Id = "claude-3-sonnet",
                Name = "claude-3-sonnet",
                DisplayName = "Claude 3 Sonnet",
                Description = "平衡性能和成本的Claude模型",
                Type = "Chat",
                ContextLength = 200000,
                InputPrice = 0.003m,
                OutputPrice = 0.015m,
                Status = "Active",
                SupportedFeatures = "Vision",
                Priority = 2,
                ProviderId = "claude"
            },
            // Gemini Models
            new Model
            {
                Id = "gemini-pro",
                Name = "gemini-pro",
                DisplayName = "Gemini Pro",
                Description = "Google的高性能Gemini模型",
                Type = "Chat",
                ContextLength = 32768,
                InputPrice = 0.0005m,
                OutputPrice = 0.0015m,
                Status = "Active",
                SupportedFeatures = "Vision",
                Priority = 1,
                ProviderId = "gemini"
            }
        };
        _context.Models.AddRange(models);

        // 4. 创建系统设置
        var systemSettings = new List<SystemSettings>
        {
            new SystemSettings
            {
                Key = "app_version",
                Value = "1.0.0",
                Description = "应用程序版本",
                DataType = "string",
                Category = "system",
                IsSystemBuiltIn = true
            },
            new SystemSettings
            {
                Key = "default_model",
                Value = "gpt-4o",
                Description = "默认使用的AI模型",
                DataType = "string",
                Category = "ai"
            },
            new SystemSettings
            {
                Key = "max_conversation_history",
                Value = "50",
                Description = "最大对话历史条数",
                DataType = "number",
                Category = "chat"
            },
            new SystemSettings
            {
                Key = "auto_save_interval",
                Value = "30",
                Description = "自动保存间隔（秒）",
                DataType = "number",
                Category = "system"
            }
        };
        _context.SystemSettings.AddRange(systemSettings);

        // 保存所有更改
        await _context.SaveChangesAsync();
        _logger.LogInformation("预制数据插入完成");
    }
} 